package com.hotacorp.opencloud.gateway.route;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hotacorp.opencloud.common.commdata.Constants;

import reactor.core.publisher.Flux;

/**
 * 自定义路由信息加载，所有的路由信息都放在redis里，网关定时从redis中读取路由信息，另外一个服务对redis中的路由信息进行维护
 */
@Component
public class CustomRouteDefinitionLocator implements RouteDefinitionLocator {
	
	@Autowired
	private StringRedisTemplate template;
	
	@Override
	public Flux<RouteDefinition> getRouteDefinitions() {
		List<Object> routes = template.boundHashOps(Constants.GATE_WAY).values();
		List<RouteDefinition> routelist = routes.stream().map(object->{
			JSONObject obj = JSON.parseObject(object.toString());
			RouteDefinition def = new RouteDefinition();
			def.setId(obj.getString("id"));
			def.setUri(URI.create(obj.getString("uri")));
			def.setOrder(obj.getIntValue("order"));
			def.setPredicates(JSON.parseArray(obj.getString("predicates"), PredicateDefinition.class));
			def.setFilters(JSON.parseArray(obj.getString("filters"), FilterDefinition.class));
			return def;
		}).collect(Collectors.toList());
		return Flux.fromIterable(routelist);
	}

}
